// pages/personInfo/index.js
const ajax = require('../../../utils/quest.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    max: 300, //最多字数 (根据自己需求改变) 
    currentWordNumber: 0,
    animation: {},
    showModalStatus: false,
    categoryVOList: [],
    cateList: [],
    selectId: '',
    selectData: {},
    purchaseVariety: '',
    categoryName: '',
    purchaseQuantity: '',
    endTime: '',
    purchaseArea: '',
    items: [{
        name: '0',
        value: '单位'
      },
      {
        name: '1',
        value: '个人',
        // checked: 'true'
      }
    ],
    arrList: [],
    personalPhotolist: [],

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  radioChange(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      demandSide: e.detail.value
    })
  },
  //字数限制 
  inputs: function (e) {
    // 获取输入框的内容
    var value = e.detail.value;
    // 获取输入框内容的长度
    var len = parseInt(value.length);
    this.setData({
      currentWordNumber: len //当前字数 
    });
    //最多字数限制
    if (len > this.data.max) return;
    // 当输入框内容的长度大于最大长度限制（max)时，终止setData()的执行
  },
  bindDateChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      endTime: e.detail.value
    })
  },
  // 采购地区
  // bindRegionChange: function (e) {
  //   console.log('picker发送选择改变，携带值为', e.detail.value)
  //   this.setData({
  //     purchaseArea: e.detail.value
  //   })
  //   var adressArr = e.detail.value;
  //   if (adressArr[1] == '北京市' || adressArr[1] == '天津市' || adressArr[1] == '上海市' || adressArr[1] == '重庆市') {
  //     adressArr[1] = '市辖区'
  //   }
  //   this.getArea(adressArr.join(","), 0);
  // },
  // 收货地区
  // bindReceiptChange: function (e) {
  //   console.log('picker发送选择改变，携带值为', e.detail.value)
  //   this.setData({
  //     receiptArea: e.detail.value
  //   })
  //   var adressArr = e.detail.value;
  //   if (adressArr[1] == '北京市' || adressArr[1] == '天津市' || adressArr[1] == '上海市' || adressArr[1] == '重庆市') {
  //     adressArr[1] = '市辖区'
  //   }
  //   this.getArea(adressArr.join(","), 1);
  // },
  // getArea: function (strUrl, type) {
  //   var that = this;
  //   var strUrls = {
  //     names: strUrl
  //   }
  //   ajax.sendRequest("/area/getAreaByNames", 'get', strUrls)
  //     .then(function (response) {
  //       var resArr = response.data.areaVOS;
  //       if (resArr.length >= 3) {
  //         var province = response.data.areaVOS[0].value;
  //         var city = undefined;
  //         var district = undefined;
  //         for (var i = 0; i < resArr.length; i++) {
  //           if (resArr[i].pid == province) {
  //             city = resArr[i].value;
  //           }
  //           if (resArr[i].pid == city) {
  //             district = resArr[i].value;
  //           }

  //         }
  //         var regionId = {
  //           province: province,
  //           city: city,
  //           district: district
  //         }
  //         // type 0的时候是采购地区
  //         if (type == 0) {
  //           console.log("type", type);
  //           console.log('regionId', regionId);
  //           that.setData({
  //             myRegionId: regionId
  //           })
  //         } else {
  //           that.setData({
  //             unitRegionId: regionId
  //           })
  //         }

  //       } else if (resArr.length == 0) {
  //         wx.showModal({
  //           title: '提示',
  //           content: '该平台目前不支持您所选区域！',
  //         })
  //       }
  //     }, function (error) {})
  // },
  bandSpecialty: function () {
    this.showModal()
    this.getTree()
  },
  getTree: function () {
    ajax.sendRequest('/category/getCategoryTree', 'get').then(res => {
      const {
        categoryVOList
      } = res.data
      const isList = []
      for (var i = 0; i < categoryVOList.length; i++) {
        for (var j = 0; j < categoryVOList[i].sonCategoryList.length; j++) {
          console.log(categoryVOList[i].sonCategoryList[j]);
          categoryVOList[i].sonCategoryList[j].isSelected = false
        }
        isList.push(categoryVOList[i])
      }
      this.setData({
        cateList: isList,
      })
    })
  },
  bandCancel() {
    this.hideModal()
  },
  bandDetermine() {
    const {
      selectData,
      categoryName
    } = this.data
    console.log('selectData', selectData);

    this.setData({
      purchaseVariety: categoryName + '>' + selectData.categoryName
    })
    this.hideModal()
  },
  // 显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  addressRelicList(e) {
    let value = e.currentTarget.dataset.id;
    console.log(' e.currentTarget.dataset', e.currentTarget.dataset);
    let categoryName = e.currentTarget.dataset.father.categoryName;
    this.setData({
      selectId: value.id, //子id
      selectData: value,
      categoryName: categoryName
    })
  },
  formSubmitLogin(e) {
    console.log(e.detail.value);
    this.setData({
      personalInformation: e.detail.value
    })
    this.save()
  },
  save() {
    const {
      selectData,
      categoryName,
      personalInformation,
      personalPhotolist,
      demandSide,
      unitRegionId
    } = this.data
    console.log("categoryName", categoryName);
    if (!demandSide) {
      return wx.showToast({
        icon: "none",
        title: '请选择需求方',
      })
    } else if (!personalInformation.purchaseName) {
      return wx.showToast({
        icon: "none",
        title: '请输入商品名称',
      })
    } else if (!personalInformation.purchaseVariety) {
      return wx.showToast({
        icon: "none",
        title: '请选择采购品种',
      })
    } else if (!personalInformation.purchaseQuantity) {
      return wx.showToast({
        icon: "none",
        title: '请输入采购数量',
      })
    } else if (!personalInformation.endTime) {
      return wx.showToast({
        icon: "none",
        title: '请选择截止时间',
      })
    } else if (!personalPhotolist.length) {
      return wx.showToast({
        icon: "none",
        title: '请上传图片',
      })
    }
    const reqbody = {
      demandSide: demandSide,
      categoryPId: selectData.pid,
      categorySId: selectData.id,
      ...personalInformation,
      ...unitRegionId,
      picUrl: personalPhotolist[0].picUrl
      // purchaseName: personalInformation.purchaseName,
      // purchaseVariety: personalInformation.purchaseVariety,
      // purchaseQuantity: personalInformation.purchaseQuantity,
      // endTime: personalInformation.endTime,
      // receiveArea: personalInformation.receiptArea,
      // describe: personalInformation.describe,
      // purchaseArea: personalInformation.receiptArea,
    }
    console.log("reqbody", reqbody);
    ajax.sendRequest('/farmerDemand/save', 'POST', reqbody).then(res => {
      console.log("新增", res);
      wx.showModal({
        title: '提示',
        content: '保存成功',
      })
      wx.navigateBack({
        delta: 1
      })
    })
  },
  // 上传
  uploadImages: function () {
    const than = this
    const {
      arrList,
      personalPhotolist
    } = than.data
    console.log('arrList', arrList);
    console.log('personalPhotolist', personalPhotolist);

    wx.chooseImage({
      count: 1,
      sizeType: ['original'], //原图
      sourceType: ['album', 'camera'], //支持选取图片
      success(res) {
        arrList.push(res.tempFiles[0])
        ajax.upLoadFiles(res.tempFiles[0].path).then(res => {
          // const imgUrl = res
          const personalPhoto = {
            'picUrl': res
          }
          personalPhotolist.push(personalPhoto)
          if (res) {
            than.setData({
              picList: arrList,
              personalPhotolist: personalPhotolist
            })
          } else {
            return wx.showToast({
              title: '系统内部错误，请联系管理员',
              icon: 'none',
            })
          }
        })
      }
    })
  },
  // 删除
  delImages: function (e) {
    const {
      personalPhotolist
    } = this.data
    console.log(personalPhotolist);
    const that = this
    const index = e.currentTarget.dataset.item
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      success: function (res) {
        if (res.confirm) {
          personalPhotolist.splice(index, 1)
          that.setData({
            personalPhotolist: personalPhotolist
          })
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})